﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Newtonsoft.Json;
using System;

namespace DotNetStar.TheKing.Infrastructure
{
    /// <summary>
    /// 使用阿里云的短信通知机制。
    /// </summary>
    public class SmsNotification : NotificationBase
    {
        /// <summary>
        /// 初始化 <see cref="SmsNotification"/> 类的新实例。
        /// </summary>
        /// <param name="mobile">接收短信的手机号码。</param>
        /// <param name="templateCode">阿里云短信服务的模版编号。</param>
        /// <param name="parameters">短信模版的参数对象，请使用匿名对象。</param>
        public SmsNotification(string mobile, string templateCode, object parameters = null)
            : base(mobile, templateCode) 
            => this.Parameter = parameters;

        public override void Send()
        {
            String product = "Dysmsapi";//短信API产品名称
            String domain = "dysmsapi.aliyuncs.com";//短信API产品域名


            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "LTAIrZWkzCZWr3We", "vQzx3tnBfOgo6pxUyWrmS1kV28FV0Y");
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                PhoneNumbers = this.To,
                //必填:短信签名
                SignName = "码农猩球",
                //必填:短信模板
                TemplateCode = this.Content,

            };

            if (Parameter != null)
            {
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = JsonConvert.SerializeObject(Parameter);
            }
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            //request.OutId = "21212121211";
            //请求失败这里会抛ClientException异常
            try
            {
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
            }
            catch (ClientException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 发送验证码通知。
        /// </summary>
        /// <param name="mobile">手机号。</param>
        /// <param name="code">验证码。</param>
        /// <returns></returns>
        public static SmsNotification SendVerifyCode(string mobile, string code)
            => new SmsNotification(mobile, "SMS_109525004", new { code });
    }
}
